<?php

namespace App\Jobs;

use App\Constant\QueueKey;
use App\Events\CollectionReceiptEvent;
use App\Events\RepayMentEvent;
use App\Models\RepayRecord;
use App\Models\RepayRecordCommon;
use App\Models\RepayRecordMonth;
use App\Models\RepaySummary;
use App\Models\UserBankCard;
use App\Models\UserGlobal;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class RepayCommonJobQueue implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $tries = 3;

    protected $id;


    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($recordId)
    {
        $this->onQueue(QueueKey::QUEUE_REPAY_COMMON);
        $this->id = $recordId;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //公共 && 资方 => 月保费 => 公共
        try {
            //获取还款记录
            $recordInfo = RepayRecord::with(['money','month','common'])->where('id',$this->id)->first();
            if(!$recordInfo){
                Log::debug('还款:请求公共接口:没有数据' . $this->id);
                return;
            }
            //判断是否处于可扣款状态
            if($recordInfo->common->status == RepayRecordCommon::STATUS_FOUR){
                //公共成功,更改状态
                if($recordInfo->period == 0){
                    RepaySummary::setNormalAllPeriodSuccess($recordInfo->common);
                }else{
                    RepaySummary::setNormalCurrentPeriodSuccess($recordInfo->common);
                }
                return;
            }elseif($recordInfo->common->status == RepayRecordCommon::STATUS_TWO){
                Log::debug('还款:请求公共接口:在队列中不是要处理的状态' . $this->id);
                return;
            }
            //判断上期是否还款成功
            $is_success = RepayRecord::isLastPeriodSuccess($recordInfo);
            if(!$is_success){
                RepayRecordCommon::where('id',$recordInfo->money->id)->update(['status' => RepayRecordCommon::STATUS_THREE,'failure' => '请还上期还款']);
                RepayRecord::where('id',$recordInfo->id)->update(['status' => RepayRecord::STATUS_THREE,'failure_status' => RepayRecord::FAILURE_STATUS_THREE,'failure_message' => '请还上期还款']);
                UserGlobal::where('uid',$recordInfo->uid)->update(['global_status' => UserGlobal::STATUS_REPAY_FAILURE]);
                Log::debug('repay_last_period_success', ['message' => json_encode($recordInfo,JSON_UNESCAPED_UNICODE)]);
                return;
            }


            //todo 判断是否是农信的
            $is_channel = RepaySummary::getLoanChannel($recordInfo->summary_id);
            if(false == $is_channel){
                $this->nongXin($recordInfo);
                DB::commit();
                return;
            }

            $month_status = $recordInfo->month->status;
            $month_amount = $recordInfo->month->amount;//月保费金额
            if($month_status != RepayRecordMonth::STATUS_FOUR && $month_amount != 0){
                //改变为轮询中,让轮询处理
                UserGlobal::where('uid',$recordInfo->uid)->update(['global_status' => UserGlobal::STATUS_REPAY_ING]);
                RepayRecord::where('id',$recordInfo->id)->update(['status' => RepayRecord::STATUS_TWO]);
                RepayRecordMonth::where('id',$recordInfo->month->id)->update(['status' => RepayRecordMonth::STATUS_TWO]);
                Log::debug('还款:公共接口判断上个接口不是成功状态');
                DB::commit();
                return;

            }

            $repayInfo = RepaySummary::select('rate','amount') -> where('id',$recordInfo->summary_id)->first();

            $hold_agreement_num = UserBankCard::getHoldAgreementNumById($recordInfo->bank_cards_id,$recordInfo->summary_id);
            if(!$hold_agreement_num){
                //协议号错误
                DB::beginTransaction();
                try{
                    RepayRecordCommon::where('id',$recordInfo->common->id)->update(['status' => RepayRecordCommon::STATUS_THREE,'failure' => '银行协议错误']);
                    RepayRecord::where('id',$recordInfo->id)->update(['status' => RepayRecord::STATUS_THREE,'failure_status' => RepayRecord::FAILURE_STATUS_TWO,'failure_message' => '银行卡错误,请选择其他银行卡']);
                    UserGlobal::where('uid',$recordInfo->uid)->update(['global_status' => UserGlobal::STATUS_REPAY_FAILURE]);
                    DB::commit();
                }catch (\Exception $e){
                    DB::rollBack();
                    Log::debug('还款:请求公共接口银行卡协议号报错' . $recordInfo->bank_cards_id);
                }
                return;
            }
            //计算罚息
            $fines_money_all = RepaySummary::getFines($recordInfo->normal_date,$repayInfo->rate['fines_rate'],$repayInfo->amount,$recordInfo->common->id);
            $recordInfo->common->fines_money = $fines_money_all['common_fines_money'];
            $recordInfo->common->relief_amount = $fines_money_all['relief_amount'];
            $lending_money = $recordInfo->common->lending_money;//利息
            $manage_money = $recordInfo->common->manage_money;//贷后管理费

            $repayment_money = 0;
            //如果为全部还清才有提前还清手续费
            if($recordInfo->pay_off == RepayRecord::PAY_OFF_TWO){
                $repayment_money = $recordInfo->common->repayment_money;
            }

            //订单编号
            $trade_no = empty($recordInfo->common->trade_no) ? RepaySummary::createTradeNo($recordInfo->uid,'common') : $recordInfo->common->trade_no;
            $recordInfo->common->trade_no = $trade_no;
            $moneyArray = [
                'lending_money' => $lending_money,//利息
                'manage_money' => $manage_money,//管理费
                'fines_money' => $recordInfo->common->fines_money,//罚息
                'repayment_money' => $repayment_money,//提前结清手续费
                'discount_amount' => $recordInfo->common->discount_amount,//折扣金额
            ];
            $res = RepaySummary::setCommon($moneyArray,$recordInfo->common->trade_no,$hold_agreement_num,$recordInfo->common->id,$recordInfo->common->period,$recordInfo->summary_id);
            $this->saveCommonStatus($recordInfo,$res);
            //更新催收方数据
            event(new RepayMentEvent($recordInfo->summary_id));
            return;
        } catch (\Exception $e) {
            \Log::debug('还款:调用公共接口失败' . $e->getFile() . '的' . $e->getLine() . '行中' . $e->getMessage() . '导致此次队列执行失败' . PHP_EOL);
        }
    }

    /**
     * Description:农信的逻辑
     * Author:lijiafei
     * @param RepayRecord $recordInfo
     */
    protected function nongXin(RepayRecord $recordInfo)
    {

        $repayInfo = RepaySummary::select('rate','amount','loan_id') -> where('id',$recordInfo->summary_id)->first();
        $userBankCard = UserBankCard::select('hold_agreement_num','uid') -> where('id',$recordInfo->bank_cards_id)->first();
        $hold_agreement_num = $userBankCard->hold_agreement_num;
        //计算罚息
        $fines_money = RepaySummary::getFines($recordInfo->normal_date,$repayInfo->rate['fines_rate'],$repayInfo->amount,$recordInfo->common->id);
        $recordInfo->common->fines_money = $fines_money['common_fines_money'];
        $recordInfo->common->relief_amount = $fines_money['relief_amount'];
        $money = RepaySummary::getOldMoney($recordInfo);
        $repayment_money = 0;
        //如果为全部还清才有提前还清手续费
        if($recordInfo->pay_off == RepayRecord::PAY_OFF_TWO){
            $repayment_money = $recordInfo->common->repayment_money;
        }

        $trade_no = empty($recordInfo->common->trade_no) ? RepaySummary::createTradeNo($recordInfo->uid,'common') : $recordInfo->common->trade_no; //订单编号
        $recordInfo->common->trade_no = $trade_no;
        //农信的总金额传过去就可以了
        $moneyArray = [
            'lending_money' => $money,//利息
            'manage_money' => 0,//管理费
            'fines_money' => 0,//罚息
            'repayment_money' => $repayment_money,//提前结清手续费
            'discount_amount' => $recordInfo->common->discount_amount,//折扣金额
        ];
        $res = RepaySummary::setCommon($moneyArray,$recordInfo->common->trade_no,$hold_agreement_num,$recordInfo->common->id,$recordInfo->common->period,$recordInfo->summary_id);
        $this->saveCommonStatus($recordInfo,$res);
        return;
    }

    protected function saveCommonStatus(RepayRecord $recordInfo,$res){
        if(!$res){
            return;
        }
        //改变状态 用户全局状态为轮询中,记录总表为轮询中,两个分表为轮询中 开启事务
        DB::beginTransaction();
        try{
            //保存罚息
            $common = $recordInfo->common;
            if($res == 1){
                //金额为0
                $common -> fines_money = $recordInfo->common->fines_money;
                $common -> trade_no = $recordInfo->common->trade_no;
                $common -> relief_amount = $recordInfo->common->relief_amount;
                $common -> save();
            }else{
                $common -> fines_money = $recordInfo->common->fines_money;
                $common -> status = RepayRecordCommon::STATUS_TWO;
                $common -> trade_no = $recordInfo->common->trade_no;
                $common -> relief_amount = $recordInfo->common->relief_amount;
                $common -> save();
                UserGlobal::where('uid',$recordInfo->uid)->update(['global_status' => UserGlobal::STATUS_REPAY_ING]);
                RepayRecord::where('id',$recordInfo->id)->update(['status' => RepayRecord::STATUS_TWO]);
                RepaySummary::checkApiNumber($recordInfo->summary_id,$recordInfo->uid,RepaySummary::COMMON_API,2);
            }

            DB::commit();
        }catch(\Exception $exception){
            Log::debug("还款:公共接口队列:还款更新UserGlobal,RepayRecord,RepayRecordCommon失败".$exception->getMessage());
            DB::rollBack();
        }
    }
}
